package socket;

import sun.nio.cs.MS1250;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * User: heihaier@xfuweng.com
 * Date: 2015/7/8
 * Time: 14:46
 */
public class ServerThread implements Runnable {

    private Socket socket;

    private BufferedReader br;

    public ServerThread(Socket socket) throws IOException {

        this.socket = socket;
        this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {

        String content = null;

        while ((content = readFromClient()) != null) {

            for (Socket s : MyServer.list) {

                try {
                    PrintStream p = new PrintStream(s.getOutputStream());
                    p.println("server : " + content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String readFromClient() {

        String result = null;

        try {
            result = socket.getPort() + " || " + br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            MyServer.list.remove(socket);
        }

        return result;
    }
}
